# 当前工具是用来生成html报告的
import sys
import os
from util import PathUtil

'''
生成html报告
title: 报告的标题 元组类型
data: 报告的数据 list类型 ,每一个元素是一个字典，字典的key是ip,value是次数
'''


def gen_html_report(title=(), data=None):
    if data is None:
        data = []
    # 根据标题和data对应的key生成报告的表格
    html = f"""
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
"""
    html += "<table border='1'>\n"
    # 标题
    html += "<tr>\n"
    for index, value in enumerate(title):
        html += f"<th>{value}</th>\n"
    html += "</tr>\n"
    # 内容
    for datum in data:
        html += "<tr>\n"

        for index, value in enumerate(title):
            val = datum[value]
            html += f"<td>{val}</td>\n"
        html += "</tr>\n"

    html += "</table>"

    html += """
    </body>
</html>
    """
    return html


'''
将生成的html保存到report文件夹下
'''


def savefile(data=None):
    # 生成html报告
    html = gen_html_report(title=("ip", "错误次数", "时间", "主机"), data=data)
    # 保存到report文件夹下
    path = PathUtil.get_root_path()
    # 判断report文件夹是否存在，如果不存在则创建
    if not os.path.exists(path + "/report"):
        os.mkdir(path + "/report")
    print("路径" + path)
    with open(path + "/report/ip访问异常报告.html", "w", encoding="utf-8") as f:
        f.write(html)
    pass


if __name__ == '__main__':
    data = [
        {"ip": "123456", "次数": 12, "时间": "2025-03-01 10:12:00"},
        {"ip": "123456", "次数": 12, "时间": "2025-03-01 10:12:00"},
        {"次数": 12, "ip": "123456", "时间": "2025-03-01 10:12:00"}
    ]
    savefile(data=data)
pass
